package com.xinqi.common.mybatis.injector.method;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.xinqi.common.mybatis.injector.enums.ExtSqlMethod;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.List;

import static java.util.stream.Collectors.joining;

/**
 * 根据 ID 更新有值字段
 *
 * @author linkai
 * @date 2019/07/16
 */
public class UpdateAllColumnById extends AbstractMethod {

    public UpdateAllColumnById() {
        this(ExtSqlMethod.UPDATE_ALL_COLUMN_BY_ID.getMethod());
    }

    /**
     * @param name 方法名
     * @since 3.5.0
     */
    public UpdateAllColumnById(String name) {
        super(name);
    }


    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        boolean logicDelete = tableInfo.isLogicDelete();
        ExtSqlMethod sqlMethod = ExtSqlMethod.UPDATE_ALL_COLUMN_BY_ID;
        final String additional = optlockVersion(tableInfo) + tableInfo.getLogicDeleteSql(true, false);
        String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
            sqlSet(logicDelete, tableInfo, ENTITY_DOT), tableInfo.getKeyColumn(),
            ENTITY_DOT + tableInfo.getKeyProperty(), additional);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
    }

    private String sqlSet(boolean logic, TableInfo table, String prefix) {
        String sqlScript = getAllSqlSet(table, logic, prefix);
        sqlScript = SqlScriptUtils.convertSet(sqlScript);
        return sqlScript;
    }

    private String getAllSqlSet(TableInfo table, boolean ignoreLogicDelFiled, final String prefix) {
        final String newPrefix = prefix == null ? EMPTY : prefix;
        List<TableFieldInfo> fieldList = table.getFieldList();
        return fieldList.stream().filter(i -> {
            if (ignoreLogicDelFiled) {
                return !(table.isLogicDelete() && i.isLogicDelete());
            }
            return true;
        }).map(i -> i.getSqlSet(true, newPrefix)).collect(joining(NEWLINE));
    }

}
